<?php 
class kdtrace_nice extends Controller {
	
	function track( $tracknum , $lang = "en"){
		
		$getdata = 'code=' . $tracknum . '&imageField.x=35&imageField.y=16';
		$url 	 = "http://www.niceexpress.net/billStatusSearch.do" ;
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $getdata);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			'Accept-Language: en_US',
			'Content-Type: application/x-www-form-urlencoded',
			'Referer: http://www.niceexpress.net/',
			'User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36' 
		));

		$result = curl_exec($ch);
        curl_close($ch);
		$rtndata = array('tracknum'=>$tracknum,'header'=>array(),'err'=>array(),'eventList'=>array());

		$rtndata['err']['errcode'] = '0';
		$w1 = strpos($result , "><strong>Type</strong><");
		$w2 = strpos($result , "</table>" , $w1);
		$rhtm = substr($result , $w1 , $w2-$w1);
		
		//$rhtm = preg_replace("/<td valign\=\"top\"><p align\=\"left\">\s*<\/p><\/td>/i" , "" , $rhtm);

		if(preg_match_all("/<td valign\=\"top\"><p align\=\"left\">(.+?)<\/p><\/td>/i", $rhtm, $matches) >0){
			//print_r($matches);
			$rtndata['header']['shipFrom']		= $matches[1][4];
			$rtndata['header']['shipTo']		= $matches[1][6];
		};
		
		$w1 = strpos($result , "><p><strong>Remark</strong></p></td>" );
		$w1 = strpos($result , "</tr>" , $w1 ) +5;
		$w2 = strpos($result , '</table>' ,$w1);
		$bdhtm = substr($result , $w1 , $w2 - $w1);
		
		$bdhtm = str_replace("\r" , "" , $bdhtm);
		$bdhtm = str_replace("\n" , "" , $bdhtm);
		$bdhtm = str_replace("	" , "" , $bdhtm);
		$bdhtm = str_replace("&nbsp;" , " " , $bdhtm);
		$bdhtm = $this->skipSpaces($bdhtm);

		preg_match_all('/<tr> <td><p align\="left"> <\/p><\/td> <td>(.+?)<\/td> <td>(.+?)<\/td> <td><p align\="left"> <\/p><\/td> <td>(.+?)<\/td> <td><p align\="left"> <\/p><\/td> <td><p>(.+?)<\/p><\/td>/i', $bdhtm, $matches);
		$count = count($matches[0]);
		if($count>0){
			for($i=0 ; $i < $count ; $i++){
				//$this->skipSpaces($matches[1][$i])
				$tt =  strtotime( strip_tags($matches[1][$i]) . " " . strip_tags($matches[2][$i]) );
				$rtndata['eventList'][$i] = array(
					"date"			=> date('Y-m-d',$tt),
					"time"			=> date('h:i:s',$tt),
					"utime"			=> $tt,
					"status"		=> trim(strip_tags($matches[4][$i])),
					"location"		=> trim(strip_tags($matches[3][$i]))
				);
			}
		}


		return $rtndata;
	}
	function skipSpaces($t){
			return  trim(preg_replace('/\s{2,}/', ' ', $t));
	}
	
}

?>